package com.redstar.HappyRefresh.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.redstar.HappyRefresh.cache.UserInfo;
import com.redstar.HappyRefresh.pojo.Result;
import com.redstar.HappyRefresh.pojo.User;
import com.redstar.HappyRefresh.service.UserService;
import com.redstar.HappyRefresh.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class InterceptorManage implements HandlerInterceptor {
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if ("OPTIONS".equals(request.getMethod())) {
            return true;
        }
        if (!JwtUtils.checkToken(request)) {
            reponseBack(Result.fail().message("请登录后操作"), response);
            return false;
        }
        Long userId = JwtUtils.getUserId(request);
        User user = userService.getById(userId);
        if (ObjectUtils.isEmpty(user)) {
            reponseBack(Result.fail().message("用户不存在"), response);
            return false;
        }
        UserInfo.set(userId);
        return true;
    }

    private void reponseBack(Result result, HttpServletResponse response) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        // 转化成JSON字符串
        response.getWriter().println(objectMapper.writeValueAsString(result));
        response.getWriter().flush();
    }
}
